package com.web;

import java.util.Map;
import java.util.regex.Matcher;
import java.util.regex.Pattern;

public class PlaceholderUtils {
    private static final Pattern PLACEHOLDER_PATTERN = Pattern.compile("\\{(.*?)\\}");
    
    /**
     * 替换字符串中的占位符{key}为对应的值
     * @param template 包含占位符的模板字符串
     * @param params 参数键值对
     * @return 替换后的字符串
     */
    public static String replacePlaceholders(String template, Map<String, Object> params) {
        if (template == null || template.isEmpty()) {
            return template;
        }
        
        Matcher matcher = PLACEHOLDER_PATTERN.matcher(template);
        StringBuffer result = new StringBuffer();
        
        while (matcher.find()) {
            String key = matcher.group(1); // 获取占位符中的key
            Object value = params.get(key);
            // 如果找到对应值则替换，否则保留原占位符
            String replacement = (value != null) ? value.toString() : matcher.group();
            matcher.appendReplacement(result, replacement);
        }
        matcher.appendTail(result);
        
        return result.toString();
    }
}